﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using MyMeta;
using System.IO;
using Liger.Generate;
public static class AjaxDbHelper
{
    public static dbDriver GetDbDriver(string dbType)
    {
        switch(dbType.ToLower())
        {
            case "access":
                return dbDriver.Access;
            default:
                return dbDriver.SQL;
        }
    }



    public static AjaxResult TryConnect(string dbType,string connectionString)
    {
        var root = new MyMeta.dbRoot();
        var driver = GetDbDriver(dbType);
        try
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new Exception("连接字符串不能为空");
            root.Connect(driver, connectionString);
            if (root.IsConnected)
            {
                return AjaxResult.Success(true);
            }
            return AjaxResult.CreateError("连接失败");
        }
        catch(Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        } 
    }


    public static AjaxResult GetDb(string dbType, string connectionString)
    {
        var root = new MyMeta.dbRoot();
        var driver = GetDbDriver(dbType);
        try
        {
            root.Connect(driver, connectionString);
            if (root.IsConnected)
            {
                return AjaxResult.Success(new
                {
                    name = root.DefaultDatabase.Name,
                    dbType = dbType,
                    connectionString = connectionString
                });
            }
            return AjaxResult.CreateError("链接失败");
        }
        catch (Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        }
    }
    public static AjaxResult GetSettings()
    {
        try
        {
            var settings = SettingXMLHelper.GetSettings();
            return AjaxResult.Success(settings);
        }
        catch (Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        }
    }

    public static AjaxResult AddDbSetting(string dbType, string connectionString)
    {
        try
        {
            if (SettingXMLHelper.ExistSetting(connectionString))
            {
                throw new Exception("此数据库链接已经存在");
            }
            var root = new MyMeta.dbRoot();
            var driver = GetDbDriver(dbType);
        
            root.Connect(driver, connectionString); 
            if (root.IsConnected)
            {
                var setting = SettingXMLHelper.AddSetting(root.DefaultDatabase.Name, dbType, connectionString);
                return AjaxResult.Success(setting);
            }
            else
            {
                return AjaxResult.CreateError("数据库链接失败");
            }
        }
        catch (Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        }
    }


    public static AjaxResult RemoveDbSetting(string connectionString)
    {
        try
        {
            SettingXMLHelper.RemoveSetting(connectionString);
            return AjaxResult.Success("删除成功");
        }
        catch (Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        }
    }

    public static AjaxResult GetTables(string dbType, string connectionString, string db)
    {
        var root = new MyMeta.dbRoot();
        var driver = GetDbDriver(dbType);
        try
        {
            root.Connect(driver, connectionString);
            if (root.IsConnected)
            {
                var tables = root.DefaultDatabase.Tables;
                var list = new List<TreeTable>();
                foreach (ITable table in tables)
                {
                    list.Add(new TreeTable()
                    {
                        name = table.Name,
                        dbType = dbType,
                        connectionString = connectionString
                    });
                }
                return AjaxResult.Success(list);
            }
            return AjaxResult.CreateError("链接失败");
        }
        catch (Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        }
    }

    public static AjaxResult GetViews(string dbType, string connectionString, string db)
    {
        var root = new MyMeta.dbRoot();
        var driver = GetDbDriver(dbType);
        try
        {
            root.Connect(driver, connectionString);
            if (root.IsConnected)
            {
                var views = root.DefaultDatabase.Views;
                var list = new List<TreeView>();
                foreach (IView view in views)
                {
                    list.Add(new TreeView()
                    {
                        name = view.Name,
                        dbType = dbType,
                        connectionString = connectionString
                    });
                }
                return AjaxResult.Success(list);
            }
            return AjaxResult.CreateError("链接失败");
        }
        catch (Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        }
    }

    public static AjaxResult GetColumns(string dbType, string connectionString, string table)
    {
        var root = new MyMeta.dbRoot();
        var driver = GetDbDriver(dbType);
        try
        {
            root.Connect(driver, connectionString);
            if (root.IsConnected)
            {
                var tables = root.DefaultDatabase.Tables;
                var list = new List<TreeColumn>();
                foreach (ITable t in tables)
                {
                    if (t.Name == table)
                    {
                        foreach (IColumn column in t.Columns)
                        {
                            list.Add(new TreeColumn()
                            {
                                name = column.Name,
                                isInPrimaryKey = column.IsInPrimaryKey,
                                isInForeignKey = column.IsInForeignKey,
                                dbType = dbType,
                                connectionString = connectionString
                            });
                        }
                        break;
                    }
                }
                return AjaxResult.Success(list);
            }
            return AjaxResult.CreateError("链接失败");
        }
        catch (Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        }
    }

    public static AjaxResult GetViewColumns(string dbType, string connectionString, string view)
    {
        var root = new MyMeta.dbRoot();
        var driver = GetDbDriver(dbType);
        try
        {
            root.Connect(driver, connectionString);
            if (root.IsConnected)
            {
                var views = root.DefaultDatabase.Views;
                var list = new List<TreeColumn>();
                foreach (IView t in views)
                {
                    if (t.Name == view)
                    {
                        foreach (IColumn column in t.Columns)
                        {
                            list.Add(new TreeColumn()
                            {
                                name = column.Name,
                                isInPrimaryKey = column.IsInPrimaryKey,
                                isInForeignKey = column.IsInForeignKey,
                                dbType = dbType,
                                connectionString = connectionString
                            });
                        }
                        break;
                    }
                }
                return AjaxResult.Success(list);
            }
            return AjaxResult.CreateError("链接失败");
        }
        catch (Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        }
    }

    private static void OutputFile(string filepath, string content)
    { 
        File.WriteAllText(filepath, content); 
    }

    public static AjaxResult Generate(string dbType, string connectionString, string path, string space, string include, bool? copyright)
    { 
        try
        {
            string[] includes = null;
            if (!string.IsNullOrEmpty(include))
            {
                includes = include.Split(',');
            }
            var root = new MyMeta.dbRoot();
            var driver = GetDbDriver(dbType);
            if (!Directory.Exists(path))
            { 
                throw new Exception("指定的文件目录不存在");
            }
            root.Connect(driver, connectionString);
            if (root.IsConnected)
            {
                var tables = root.DefaultDatabase.Tables; 
                foreach (ITable t in tables)
                {
                    if (includes != null && !includes.Contains(t.Name)) 
                        continue;
                    var helper = new NVelocityHelper();
                    helper.Add("Table", new TableBase(t));
                    helper.Add("Namespace", space);
                    helper.Add("Copyright", copyright != null && copyright.Value ? true : false);
                    var code = helper.Output("entity.vtl");
                    OutputFile(path + "/" + DbTemplateHepler.GetClassName(t.Name) + ".cs", code);
                }

                var views = root.DefaultDatabase.Views;
                foreach (IView v in views)
                {
                    if (includes != null && !includes.Contains(v.Name)) 
                        continue;
                    var helper = new NVelocityHelper();
                    helper.Add("Table", new ViewBase(v));
                    helper.Add("Namespace", space);
                    helper.Add("Copyright", copyright != null && copyright.Value  ? true : false);
                    var currentPath = path;
                    var code = helper.Output("entity.vtl");
                    OutputFile(path + "/" + DbTemplateHepler.GetClassName(v.Name) + ".cs", code);
                } 
            }
            return AjaxResult.Success("生成成功");
        }
        catch (Exception err)
        {
            return AjaxResult.CreateError(err.Message);
        }
    }
} 
 